package leetcode.number;

import java.util.*;

public class ThreeSum {

    public static List<List<Integer>> threeSum(int[] nums) {
        //结果集
        List<List<Integer>> res = new ArrayList<>();
        if (nums != null && nums.length > 2) {
            Arrays.sort(nums);
            for (int index = 0; index < nums.length; index++) {

                if (index != 0 && nums[index] == nums[index - 1]) {
                    continue;
                }

                int head = index + 1;
                int tail = nums.length - 1;
                while (head < tail) {
                    if (head > index + 1 && nums[head] == nums[head - 1]) {
                        head++;
                        continue;
                    }


                    int first = nums[index];
                    int second = nums[head];
                    int third = nums[tail];

                    System.out.println("first:"+ first + " second:" + second + " third:" + third);

                    int result = first + second + third;
                    if (result > 0) {
                        tail--;
                    } else if (result < 0) {
                        head++;
                    } else {
                        if (first <= second && second <= third) {
                            List<Integer> integerList = new ArrayList<>();
                            integerList.add(first);
                            integerList.add(second);
                            integerList.add(third);
                            res.add(integerList);
                        }
                        head++;
                        tail--;
                    }
                }

            }
        }
        return res;
    }
}
